package com.llu.csrf;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.llu.demo.entity.Result;
import com.llu.demo.entity.User;
import com.llu.demo.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

@RestController
@RequestMapping("/csrf")
public class CsrfController {

    @Resource
    private UserService userService;

    // 修改个人信息
    @RequestMapping("/update/json")
    public Result updateJson(HttpServletRequest  request) throws IOException {
        // 获取请求体内容
        BufferedReader reader = request.getReader();
        StringBuilder json = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
//        解析成user
        // 解析JSON数据
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(json.toString(), User.class);
        userService.update(user);
        return Result.ok();
    }
    @RequestMapping("/update")
    public Result update(@RequestBody User user)  {

        userService.update(user);

        return Result.ok();
    }
    // 展示个人信息
    @RequestMapping("/show")
    public Result<User> show(String id , HttpServletRequest  request) {
//        验证session
        if (StringUtils.isEmpty(request.getSession().getAttribute("user") )){
            return Result.error("未登录");
        }

        User user = userService.queryById(Integer.parseInt(id));
        return Result.ok(user);
    }

    // login
    @RequestMapping("/login")
    public Result login(HttpServletRequest  request) {
//        通过requets设置cookie
        request.getSession().setAttribute("user", "admin");
        return Result.ok();
    }
    // 退出
    @RequestMapping("/logout")
    public Result logout(HttpServletRequest  request) {
//        通过requets设置cookie
        request.getSession().removeAttribute("user");
        return Result.ok();
    }



}
